package com.example.zluserservice.framework.config;

import com.example.zluserservice.framework.properties.SecurityConfigProperties;
import com.example.zluserservice.framework.security.JwtTokenAuthorizationManager;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author zhenliu（孙凌岳）
 * @Description 权限核心配置类
 * @Date 2025/6/15 16:42
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties(SecurityConfigProperties.class)
public class SecurityConfig {
    @Resource
    private JwtTokenAuthorizationManager jwtTokenAuthorizationManager;

    @Resource
    private SecurityConfigProperties securityConfigProperties;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        List<String> ignoreUrl = securityConfigProperties.getIgnoreUrl();

        http.authorizeHttpRequests()
                .antMatchers(ignoreUrl.toArray(new String[ignoreUrl.size()]))
                .permitAll().anyRequest().access(jwtTokenAuthorizationManager);

        //关闭csrf防护，防止post出问题
        http.csrf().disable();
        //关闭session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //关闭缓存
        http.headers().cacheControl().disable();

        return http.build();
    }

    /**
     * spring 管理AuthenticationManager
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
